package cn.fzkj.stm07;

import akka.actor.AbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.transactor.Coordinated;
import scala.concurrent.stm.Ref;
import scala.concurrent.stm.japi.STM;

/**
 * @ author mr
 * @ description
 * @ since 2024/12/2
 */
public class EmployeeActor extends AbstractActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);

    private final Ref.View<Integer> count = STM.newRef(20);//员工账户

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(Coordinated.class, msg -> {
                    int downCount = (int) msg.getMessage();//员工增加的工资

                    try {//注意这里异常要及时处理，否则异常会一直扩散，导致回退到系统刚启动时的初始状态！
                        msg.atomic(() -> STM.increment(count, downCount));//Employee增加工资
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                })
                .matchEquals("getCount", msg -> {
                    getSender().tell(count.get(), getSelf());
                })
                .matchAny(this::unhandled)
                .build();
    }
}
